package com.learn.english.controller;


import com.learn.english.domain.R;
import com.learn.english.exception.BusinessException;
import com.learn.english.model.entity.ChatSession;
import com.learn.english.model.param.Emitters;
import com.learn.english.model.param.Messages;
import com.learn.english.service.impl.LLMServiceImpl;
import com.learn.english.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.List;

/**
 * @author TISNIW
 * @version 1.0
 * @date 2024/8/16 10:58
 * @desc LLMController
 */
@RestController
@Slf4j
@RequestMapping("/llm")
public class LLMController {
    @Autowired
    private LLMServiceImpl llmService;
    /**
     * 聊天
     * @param model
     * @param prompt
     * @param sessionId
     * @param think
     * @return
     */
    @GetMapping("/chat")
    public R<String> chat(@RequestParam String model, @RequestParam String prompt, @RequestParam String sessionId, @RequestParam Boolean think){
        try{
            return R.ok(llmService.chat(model,prompt,sessionId,think));
        }catch (BusinessException e){
            return R.fail(e.getR());
        }
    }
    //创建新的会话
    @GetMapping("/new")
    public R<String> newSession(HttpServletRequest request){
        Long userId = getUserId(request);
        return R.ok(llmService.newSession(userId));
    }
    //获取会话列表
    @GetMapping("/list")
    public R<List<ChatSession>> listSession(HttpServletRequest request){
        Long userId = getUserId(request);
        log.info("userId:{}",userId);
        return R.ok(llmService.listSession(userId));
    }



    //删除会话记录
    @GetMapping("/delete")
    public R<String> deleteSession(HttpServletRequest request, @RequestParam String sessionId){
        Long userId = getUserId(request);
        return R.ok(llmService.deleteSession(userId, sessionId));
    }
    //获取会话记录
    @GetMapping("/get")
    public R<List<Messages>> getMessages(HttpServletRequest request, @RequestParam String sessionId){
        Long userId = getUserId(request);
        return R.ok(llmService.getMessages(userId, sessionId));
    }
    /**
     * 获取回复
     * @param sessionId
     * @return
     */
    @GetMapping(value = "/reply", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> getReply(@RequestParam String sessionId) {
        return Flux.create(emitter -> {
            Emitters.addEmitter(sessionId, emitter);
            emitter
                    .onRequest(n -> {
                    })
                    .onDispose(() -> Emitters.removeEmitter(sessionId))
                    .onCancel(() -> Emitters.removeEmitter(sessionId));
        });
    }
    private Long getUserId(HttpServletRequest request) {
        // 从request中获取拦截器解析好的userId
        Object userIdObj = request.getAttribute("userId");
        if (userIdObj == null) {
            throw new RuntimeException("用户未认证");
        }
        return Long.valueOf(userIdObj.toString());
    }
}
